package com.karrysong.answerapplication.activities;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.karrysong.answerapplication.MyApplication;
import com.karrysong.answerapplication.R;
import com.karrysong.answerapplication.beans.Question;
import com.karrysong.answerapplication.fragments.AnswerFragment;
import com.karrysong.answerapplication.utils.LogUtils;
import com.karrysong.answerapplication.utils.SPUtils;
import com.karrysong.answerapplication.utils.ToastUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.OnClick;

public class AnswerActivity extends BaseActivity implements Chronometer.OnChronometerTickListener {


    @BindView(R.id.vp_answer)
    ViewPager vp_answer;
    @BindView(R.id._chro_exam)
    Chronometer chronometer;
    @BindView(R.id.testView)
    TextView testView;
    @BindView(R.id.topStatus)
    LinearLayout topStatusLayout;

    private ArrayList<Fragment> fragmentlists;
    private int minute = 0;
    private int second = 0;
    private AlertDialog.Builder builder;
    private ArrayList<String> a;
    private List<Question> questions = new ArrayList<>();
    private int nowpager = 0;
    private List<Question> messages;
    private int type, questionType;
    private boolean isTest;
    private int exit = 0;

    @Override
    int getLayoutId() {
        return R.layout.activity_answer;
    }

    @Override
    void getPreIntent() {
//        获取传递来的变量
        type = getIntent().getIntExtra("type" ,4);
        if (type == 0){
            isTest = true;
            testView.setVisibility(View.VISIBLE);
        }
        questionType = getIntent().getIntExtra("questionType", 10);
        LogUtils.i(type + "  --  " + questionType);
    }

    @Override
    void initView() {

        hideNavKey(this);

        //动态设置状态栏高度
        int identifier = getResources().getIdentifier("status_bar_height", "dimen", "android");
        int dimensionPixelOffset = getResources().getDimensionPixelOffset(identifier);
        topStatusLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dimensionPixelOffset));


        if (isTest){
            ToastUtils.showLong("考试时间10分钟，到时自动交卷！！！");
            SPUtils.put(AnswerActivity.this, "isTest", true);
        }else {
            SPUtils.put(AnswerActivity.this, "isTest", false);
        }
//      联网获取数据
        initNet(type, questionType);

        vp_answer.setOnPageChangeListener(new MyOnPageChangeListener());
        setChronometer();
    }

    /**
     * 设置计时器
     */
    private void setChronometer() {
        chronometer.setText(nowTime());
        chronometer.start();
        chronometer.setOnChronometerTickListener(this);
    }

    /**
     * 计时器规则
     *
     * @param chronometer
     */
    @Override
    public void onChronometerTick(Chronometer chronometer) {
        second++;

        if (minute == 9 && second < 3){
            ToastUtils.showLong("还有一分钟考试结束，到时会自动交卷");
        }
        if (minute == 10 && isTest){
            ToastUtils.showLong("考试结束");
            getGrade();
            return;
        }
        if (second == 59) {
            minute++;
            second = 00;

        }
    }

    /**
     * 现在时间
     *
     * @return
     */
    private String nowTime() {
        if (second < 10) {
            return (minute + ":0" + second);
        } else {
            return (minute + ":" + second);
        }
    }

    /**
     * 初始化网络连接
     *
     * @param type
     */
    private void initNet(int type, int questionType) {
        a = new ArrayList<>();
        fragmentlists = new ArrayList<>();
        LogUtils.e("initNet: 开始联网…………");
        //进度条对话框
        final ProgressDialog progressDialog = new ProgressDialog(AnswerActivity.this, R.style.AppTheme_Dark_Dialog);
        progressDialog.setIndeterminate(true);
        progressDialog.setMessage("获取题目中...");
        progressDialog.setCancelable(false);
        progressDialog.show();

        SQLiteDatabase daoInstant = MyApplication.getDaoInstant();
        Cursor cursor = null;
        if (!isTest){
            SharedPreferences preferences = getSharedPreferences("test", MODE_PRIVATE);
            int anInt = preferences.getInt(questionType + "_" + type, 1);
            if (type == 4){
                cursor = daoInstant.query("tb_question", null, "questionType = ? ", new String[]{questionType + ""}, null, null, null);
            }else {
                cursor = daoInstant.query("tb_question", null, "type = ? and questionType = ? ", new String[]{type + "", questionType + ""}, null, null, null);
            }
            while (cursor.moveToNext()){
                Question question = getQuestion(cursor);
                questions.add(question);
                fragmentlists.add(new AnswerFragment(question));
                a.add(question.getObjectId());
            }
            //                        设置适配器
            vp_answer.setAdapter(new MainAdapter(getSupportFragmentManager()));
            if (cursor.getCount() > 0){
                vp_answer.setCurrentItem(anInt - questions.get(0).getTypeIndex());
                nowpager = anInt - questions.get(0).getTypeIndex();
            }
        }else{
            cursor = daoInstant.query("tb_question", null, "questionType = ? ", new String[]{questionType + ""}, null, null, null);
            List<Question> questionArrayList = new ArrayList<>();
            int t1 = 0, t2 = 0, t3 = 0;
            while (cursor.moveToNext()){
                Question question = getQuestion(cursor);
                questionArrayList.add(question);
                if (question.getType() == 1){
                    t1++;
                }
                if (question.getType() == 2){
                    t2++;
                }
                if (question.getType() == 3){
                    t3++;
                }
            }

            Collections.sort(questionArrayList, new Comparator<Question>() {
                @Override
                public int compare(Question o1, Question o2) {
                    return o1.getType() - o2.getType();
                }
            });

            if (t1 >= 50 && t2 >= 10 && t3 >= 10){
                int t = 10, s = 0;
                Random random = new Random();
                while (t-- > 0){
                    s += random.nextInt((t1 / 10)) + 1;
                    questions.add(questionArrayList.get(s));
                }
                t = 5;
                s = t1;
                while (t-- > 0){
                    s += random.nextInt((t2 / 5)) + 1;
                    questions.add(questionArrayList.get(s));
                }
                t = 5;
                s = t1 + t2;
                while (t-- > 0){
                    s += random.nextInt((t3 / 5)) + 1;

                    questions.add(questionArrayList.get(s));
                }
                for (Question question : questions) {
                    fragmentlists.add(new AnswerFragment(question));
                    a.add(question.getObjectId());
                }
                //                        设置适配器
                vp_answer.setAdapter(new MainAdapter(getSupportFragmentManager()));
                nowpager = 0;
            }else {
                ToastUtils.showLong("题库数据异常，无法考试！");
                finish();
            }
        }

        progressDialog.dismiss();
        LogUtils.e("initNet: 联网结束…………");
    }

    public static void hideNavKey(Context context) {
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) {
            View v = ((Activity) context).getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = ((Activity) context).getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(uiOptions);
        }

    }

    private Question getQuestion(Cursor cursor) {
        Question question = new Question();
        question.setObjectId(cursor.getString(0));
        question.setIndex(cursor.getInt(1));
        question.setType(cursor.getInt(2));
        question.setTypeIndex(cursor.getInt(3));
        question.setQuestionType(cursor.getInt(4));
        question.setTitle(cursor.getString(5));
        question.setaOption(cursor.getString(6));
        question.setbOption(cursor.getString(7));
        question.setcOption(cursor.getString(8));
        question.setdOption(cursor.getString(9));
        question.setAnswer(cursor.getString(10));
        question.setAnalysis(cursor.getString(11));
        return question;
    }


    @OnClick({R.id._btn_previous, R.id._btn_submit, R.id._btn_next})
    public void onViewClicked(View view) {
        SharedPreferences.Editor editor = getSharedPreferences("test", MODE_PRIVATE).edit();
        switch (view.getId()) {
//            点击上一题按钮
            case R.id._btn_previous:
//                如果是第一题，则谈吐司提醒，否则上移一道题
                if (nowpager == 0) {
                    ToastUtils.showShort("已经到头啦!");
                } else {
                    vp_answer.setCurrentItem(--nowpager);
                    testView.setText("考试环境：" + (nowpager +1) + "/" + questions.size());
                }
                //修改当前做题序号
                editor.putInt(questionType + "_" + type, questions.get(nowpager).getTypeIndex());
                editor.commit();
                editor.apply();
                break;
//            点击提交按钮
            case R.id._btn_submit:
//                简答题不进行提交评分
//                否则初始化并展示提交对话框
                initAlertDialog();
                builder.show();
                break;
//            点击下一题按钮
            case R.id._btn_next:
//                如果是最后一题，则谈吐司提醒，否则下移一道题
                if (nowpager == fragmentlists.size() || nowpager == questions.size() - 1) {
                    ToastUtils.showShort("已经是最后一题了!");
                } else {
                    vp_answer.setCurrentItem(++nowpager);
                    testView.setText("考试环境：" + (nowpager +1) + "/" + questions.size());
                }
                //修改当前做题序号
                editor.putInt(questionType + "_" + type, questions.get(nowpager).getTypeIndex());
                editor.commit();
                editor.apply();
                break;

        }
    }

    /**
     * viewpager适配器
     */
    class MainAdapter extends FragmentPagerAdapter {

        public MainAdapter(FragmentManager fm) {
            super(fm);
        }


        //获取条目
        @Override
        public Fragment getItem(int position) {
            return fragmentlists.get(position);
        }

        //数目
        @Override
        public int getCount() {
            return fragmentlists.size();
        }
    }


    // 弹出是否确认交卷的对话框
    private void initAlertDialog() {
        //新建对话框
        builder = new AlertDialog.Builder(AnswerActivity.this);
        builder.setTitle("提示");
        builder.setMessage("是否确定交卷?");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                getGrade();
            }

        });
        builder.setNegativeButton("取消", null);
    }

    /**
     * viewpager监听事件
     */
    private class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            nowpager = position;
            testView.setText("考试环境：" + (nowpager +1) + "/" + questions.size() + "  考试时间：10分钟.");

            //修改当前做题序号
            SharedPreferences.Editor editor = getSharedPreferences("test", MODE_PRIVATE).edit();
            editor.putInt(questionType + "_" + type, questions.get(position).getTypeIndex());
            editor.commit();
            editor.apply();
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    @Override
    public void onBackPressed() {

        if (isTest){
            new AlertDialog.Builder(AnswerActivity.this).setTitle("考试")
                    .setMessage("您正在考试，确定退出？")
                    .setPositiveButton("退出", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            isTest = false;
                            finish();
                        }
                    }).setNegativeButton("取消", null)
                    .show();
        }else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        exit++;
        if (isTest) {
            if (exit < 3){
                ToastUtils.showLong("系统检测到您退出" + exit + "次，退出三次将自动交卷！！！");
            }else {
                getGrade();
            }
        }
    }

    private void getGrade(){
        //                计算分数
        int grade = 0, allGrade = 0;
        for (Question question : questions) {
            if (question.getMyAnswer() != null){
                if (question.getAnswer().equals(question.getMyAnswer())){
                    grade += 1;
                }
                allGrade += 1;
            }
        }

        if (isTest){
            allGrade = 20;
        }
        //防止继续提示退出次数
        isTest = false;

//                传递分数
        Intent intent = new Intent(AnswerActivity.this, GradeActivity.class);
        intent.putExtra("grade", grade);
        intent.putExtra("allGrade", allGrade);
        intent.putExtra("type", type);
        intent.putExtra("questionType", questionType);
        startActivity(intent);
        finish();
    }

}